package vn.lumi.smarthome.service;

import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import vn.lumi.smarthome.LumiHome;
import vn.lumi.smarthome.service.SmartHomeService.*;

public class TransmitThread extends Thread{
	
	OutputStream os;
	Handler UIHandler;
	private static Handler mHandler;
	private ArrayList<byte[]> MsgQueue = new ArrayList<byte[]> (); //save content of messages
	static boolean isContinue = false;
	LumiHome myApp;
	
	public void Restart(){
		Log.d("TransmitThread","restarted");
		isContinue = true;
	}
	
	public static void End(){
		isContinue = false;
		mHandler.getLooper().quit();
		Log.d("Transmit Thread","end");
		Thread.currentThread().interrupt();
		return;
	}
	
	public TransmitThread(LumiHome myApp, Handler UIHandler){
	
//		this.os = os;
		this.UIHandler = UIHandler;
		this.isContinue = true;
		this.myApp = myApp;
		
		Log.d("Transmit Thread", "created");
	}
	
	public Handler getHandler(){
		return mHandler;
	}
	
	@Override
	public void run() {
		super.run();
		Looper.prepare();
		mHandler = new Handler(){
			   @Override
		        public void handleMessage(Message inputMessage) {        
		            switch (inputMessage.what) {                
		                case SmartHomeService.SER2TRAN_NEW_MSG:
		                	Bundle b = new Bundle();
		                	b = inputMessage.getData();
		                	Log.d("TransmitThread","Service: New Msg= " + Arrays.toString(b.getByteArray(SmartHomeService.MESSAGE)));
		                	if(b!= null){
		                		byte[] Msg = b.getByteArray(SmartHomeService.MESSAGE);
		                		try {
		        					LumiHome.os.write(Msg);
		                        	Log.d("TransmitThread","Send to HC: Msg = " + Arrays.toString(Msg));
		                        	Log.d("ReceiveThread","state = " + ReceiveDataThread.state);
		        				} catch (IOException e) {
		        					// TODO Auto-generated catch block
		        					e.printStackTrace();
		                        	Log.d("TransmitThread","Send HC failed Msg = " + Arrays.toString(Msg));					
		        				}
		                	}	                	
		                    break; 
		                default:
		                    super.handleMessage(inputMessage);
		                    break;
		            }		            
		        }
			};				
		Looper.loop();
	}
	
	 

}
